package com.smh.yunpicturebackend.config;

import com.smh.yunpicturebackend.interceptors.AuthInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * @author shiminghui
 * @date 2025/6/14 21:11
 * @description: web  mvc 配置
 */
@Slf4j
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    private List<String> excludePathPatterns = new ArrayList<>();

    @PostConstruct
    public void init() {
        // 从文件中读取不需要拦截的url
        InputStream inputStream = getClass().getClassLoader().getResourceAsStream("exclude.conf");
        if (inputStream == null) {
            log.error("exclude.conf not found");
            return;
        }
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));) {
            String line;
            while ((line = reader.readLine()) != null) {
                excludePathPatterns.add(line.trim());
            }
        } catch (IOException e) {
            log.error("exclude.conf read error");
        }
        log.info("excludePathPatterns: {}", excludePathPatterns);
    }


    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        registry.addInterceptor(new AuthInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns(excludePathPatterns);

    }
}
